/*
 * @Description: 表格Hook
 * @Author: seadon
 * @LastEditors: qiyu qiyu@byteluck.com
 * @Date: 2021-07-10 13:43:53
 * @LastEditTime: 2023-06-26 21:11:29
 */
import { reactive, toRef, toRefs, toRaw, unref, computed } from 'vue'
import { cloneDeep, dropWhile } from 'lodash'
import {
	ListTypeEnum,
	orderEnum,
	sourceType,
	taskTypeEnum,
} from '@/constant/enums/processCenter'
import {
	PaginationProps,
	SorterResult,
} from '@/entry_desktop/components/BaseTable/types'
import { isString } from '@/utils'
import { Key, ISelectState, IUseTable, IOrderType } from '../type'
import { Columns, typeColumnMaps } from '../constant'
import { client, path } from '@/utils'

export default function useTable({
	tenantDetail,
	activeTab,
	onGetList,
	toolElRef,
	toolElRef2,
	tableElRef,
	tempQueryInfo,
}: IUseTable) {
	// const selectState: ISelectState = reactive({
	// 	selectedRowKeys: [],
	// 	selectedRows: [],
	// })
	// const selectedRowKeysRef = toRef(selectState, 'selectedRowKeys')
	const haveRowSelection = [
		taskTypeEnum.TodoTask,
		taskTypeEnum.AgentTodo,
		taskTypeEnum.Drafts,
	]
	const hasRowSelection = computed(
		() =>
			(unref(tenantDetail) as any).tenant_auth?.batch_approve &&
			haveRowSelection.includes(unref(activeTab))
	)

	const rowKeyRef = computed(() =>
		unref(activeTab) === taskTypeEnum.TodoTask ||
		unref(activeTab) === taskTypeEnum.AgentTodo
			? 'task_instance_id'
			: unref(activeTab) === taskTypeEnum.Drafts
			? 'draft_id'
			: 'process_instance_id'
	)

	const columnsRef = computed(() => {
		const columnObj = typeColumnMaps[unref(activeTab)]
		const columnName = isString(columnObj)
			? columnObj
			: (columnObj as any)?.[
					unref((unref(toolElRef) || unref(toolElRef2))?.selectTypeRef)
			  ]
		let column: Recordable<any>[] = (Columns as any)[columnName]
		// 展示复选框时，列宽度处理
		if (unref(hasRowSelection)) {
			const tableWidth =
				unref(tableElRef)?.$el?.offsetWidth ?? document.body.offsetWidth
			column = column.map(item => ({
				...item,
				// width: item.width ? (item.width * (tableWidth - 88)) / 1030 : undefined,
			}))
		}
		return column
	})

	// 选择列变更
	// const handleSelectChange = (
	// 	selectedRowKeys: Key[],
	// 	selectedRows: Recordable<any>[]
	// ) => {
	// 	selectState.selectedRowKeys = selectedRowKeys
	// 	selectState.selectedRows = selectedRows
	// }

	// 设置选择列
	// const handleSetSelectState = (selectArr: []) => {
	// 	const resultDataArr = selectArr.map((item: any) => {
	// 		return item.task_instance_id
	// 	})
	// 	selectState.selectedRowKeys = resultDataArr
	// 	selectState.selectedRows = selectArr
	// }

	const getCheckboxProps = (record: any) => ({
		disabled:
			(unref(activeTab) === taskTypeEnum.AgentTodo &&
				!record.allow_batch_approval) ||
			(unref(activeTab) === taskTypeEnum.TodoTask &&
				!record.allow_batch_approval),
	})

	// 选择功能的配置
	const rowSelection = {
		fixed: true,
		// selectedRowKeys: selectedRowKeysRef,
		// onChange: handleSelectChange,
		getCheckboxProps,
	}

	// 清空选择项
	const handleClearSelect = () => {
		// selectState.selectedRowKeys = []
		// selectState.selectedRows = []
	}

	// 草稿箱编辑
	const handleEditDraft = (record: Recordable<any>) => {
		let openUrl = path.getFullPath(
			`/apps/desktop/sapp/${record?.app_id}/sappId/${record?.form_key}/${record?.data_uid}?type=edit`
		)
		if (sourceType.External === record?.['source_type']) {
			openUrl = record?.['page_link']
		}
		// window.open(openUrl)
		client.openWindow(openUrl + '&refresh_processcenter')
	}

	// 行操作
	const handleOperateRow = (record: Recordable<any>) => {
		return {
			style: {
				'background-color': record.currentLineHightFlag ? '#EBF1FF' : '',
			},
			onClick: () => {
				const openUrl = record?.relative_url
				if (taskTypeEnum.Drafts === unref(activeTab)) {
					return handleEditDraft(record)
				}
				// 不太完善，无法知道页面什么时候已读，暂定2秒钟
				else if (
					(taskTypeEnum.TaskNotice === unref(activeTab) ||
						taskTypeEnum.AgentNotice === unref(activeTab)) &&
					unref(tempQueryInfo)?.[unref(activeTab)]?.listType !==
						ListTypeEnum.DONE
				) {
					setTimeout(() => window.updatePortalList(), 2000)
				}

				client.openWindow(openUrl)
			},
		}
	}

	// 表格Change事件
	const handleTableChange = (
		pagination: PaginationProps,
		filters: Partial<Recordable<string[]>>,
		sorter: SorterResult
	) => {
		let timeSort = ''
		let startTimeSort = ''
		const orderType: IOrderType = {
			descend: orderEnum.DESC,
			ascend: orderEnum.ASC,
		}

		if (unref(activeTab) === taskTypeEnum.TodoTask) {
			const orderColumn: IOrderType = {
				node_name: '',
				submit_date: '',
			}
			orderColumn[sorter.field] = orderType[sorter.order]
			timeSort = orderColumn.node_name
			startTimeSort = orderColumn.submit_date
		} else if (
			[
				taskTypeEnum.DoneTask,
				taskTypeEnum.TaskNotice,
				taskTypeEnum.AgentTodo,
			].includes(unref(activeTab))
		) {
			const isStartTime = sorter.field === 'department'
			const orderValue = orderType[sorter.order]

			timeSort = !isStartTime ? orderValue : ''
			startTimeSort = isStartTime ? orderValue : ''
		} else {
			timeSort = orderType[sorter.order]
			startTimeSort = ''
		}
		onGetList({
			time_sort: timeSort,
			start_time_sort: startTimeSort,
			status: unref(tempQueryInfo)?.[unref(activeTab)]?.status || 'approve',
			type: unref(tempQueryInfo)?.[unref(activeTab)]?.listType || 'todo',
		})
	}

	return {
		// ...toRefs(selectState),
		rowKeyRef,
		columnsRef,
		rowSelection,
		hasRowSelection,
		handleEditDraft,
		handleOperateRow,
		handleTableChange,
		// handleSetSelectState,
	}
}
